package edu.udo.sopra10.chaturaji.events;

import java.util.ArrayList;
import java.util.Collections;
import java.util.EventListener;
import java.util.List;

/**
 * Event listener list object that provides a thread safe list.
 * 
 * @author Patrick Westerhoff
 * 
 * @param <T> EventListener type.
 */
public class EventListenerList<T extends EventListener>
{
	private transient ArrayList<T> listeners;
	
	/**
	 * Adds the event listener to the list.
	 * 
	 * @param listener the event listener to add.
	 */
	public void addListener ( T listener )
	{
		if ( listener == null )
			return;
		
		synchronized ( this )
		{
			if ( listeners == null )
			{
				listeners = new ArrayList<T>();
				listeners.add( listener );
				return;
			}
			
			ArrayList<T> newList = new ArrayList<T>( listeners );
			newList.add( listener );
			listeners = newList;
		}
	}
	
	/**
	 * Removes the event listener from the list.
	 * 
	 * @param listener the event listener to remove
	 */
	public void removeListener ( Object listener )
	{
		if ( listener == null )
			return;
		
		synchronized ( this )
		{
			if ( listeners == null || !listeners.contains( listener ) )
				return;
			
			ArrayList<T> newList = new ArrayList<T>( listeners );
			newList.remove( listener );
			listeners = newList.size() > 0 ? newList : null;
		}
	}
	
	/**
	 * Returns a list of all event listeners
	 * 
	 * @return list of event listeners
	 */
	public List<T> getListeners ()
	{
		synchronized ( this )
		{
			if ( listeners == null || listeners.isEmpty() )
				return Collections.emptyList();
			
			return new ArrayList<T>( listeners );
		}
	}
}
